/*
 * This source code is part of TWaver 4.0
 *
 * Serva Software PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Copyright 2002 - 2011 Serva Software. All rights reserved.
 */

package demo.table.explorer;

import java.io.File;
import java.util.Date;

import javax.swing.JLabel;
import javax.swing.filechooser.FileSystemView;

import twaver.Element;
import twaver.Node;
import twaver.TDataBox;
import twaver.tree.LazyLoader;

public class FileLoader implements LazyLoader{
	
	private TDataBox box = null;
	private JLabel label = null;
	private FileSystemView fileSystemView = null;

	public FileLoader(TDataBox box, JLabel label){
		this.box = box;
		this.label = label;
		this.fileSystemView = FileSystemView.getFileSystemView();
		
		// load first layer elements
		File[] files = fileSystemView.getRoots();
		for(int i=0; i<files.length; i++){
			createElement(files[i], null);
		}
	}
	
	private void createElement(File file, Element parent){
		boolean isLeaf = true;
		boolean isLoaded = true;		
		if(file.isDirectory()){
			File[] files = fileSystemView.getFiles(file, false);
			if (files != null && files.length > 0) {
				isLeaf = false;
				isLoaded = false;
			}
		}
		FileInfo info = new FileInfo();
		info.setFile(file);
		info.setLeaf(isLeaf);
		info.setLoaded(isLoaded);
		info.setFileName(fileSystemView.getSystemDisplayName(file));
		info.setFileType(fileSystemView.getSystemTypeDescription(file));
		info.setLastModified(new Date(file.lastModified()));
		if(file.isFile()){
			info.setFileSize(file.length());
		}else{
			info.setFileSize(-1);
		}
		
		Node element = new Node();	
		element.putElementTreeIcon(fileSystemView.getSystemIcon(file));
		element.setBusinessObject(info);
		if(parent != null){
			parent.addChild(element);
		}
		box.addElement(element);
		label.setText("The number of data in the DataBox:" + box.size());
	}
	
	// load children
	public void load(Element element) {
		FileInfo info = (FileInfo)element.getBusinessObject();
		File file = info.getFile();
		if(file.isDirectory()){
			File[] files = fileSystemView.getFiles(file, true);
			if (files != null) {
				for (int i = 0; i < files.length; ++i) {
					createElement(files[i], element);
				}
			}
		}
		info.setLoaded(true);
	}
	
	// check whether or not children is loaded.
	public boolean isLoaded(Element element) {
		FileInfo info = (FileInfo)element.getBusinessObject();
		return info.isLoaded();
	}
	
	// check whether or not the element has child
	public boolean isLeaf(Element element) {
		FileInfo info = (FileInfo)element.getBusinessObject();
		return info.isLeaf();
	}
}